package common.web.action;

import java.text.MessageFormat;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import common.log.util.LogModule;
import common.log.util.LogType;
import common.log.vo.WebLog;
import common.rbac.po.User;
import common.security.web.util.SecurityUtil;
import common.util.JSONUtils;
import common.web.vo.Result;

@Controller
@RequestMapping("/system/self")
public class SelfAction extends CommonAction {

	@RequestMapping("/view")
	@ResponseBody
	public Result view() {
		User user = this.baseService.get(User.class, SecurityUtil.getUserId());
		if (null == user) {
			return Result.fail("用户不存在");
		}
		Result res = Result.createResult(user);
		return res;
	}

	@RequestMapping("/update")
	@ResponseBody
	public Result save(@RequestBody JSONObject json) {
		JSONObject ju = json.getJSONObject("entity");
		User user = JSONUtils.toJavaObject(ju, User.class);

		if (null != user) {
			WebLog log = new WebLog(LogModule.USER, LogType.UPDATE, "操作失败");
			try {
				this.baseService.update(user);
				;
				log.setSuccess(MessageFormat.format("修改自己信息[{0}]成功!", user.getName()));
			} catch (Exception e) {
				logger.error("", e);
				return Result.fail("数据错误，请刷新后重试");
			} finally {
				this.saveLog(log);
			}
		} else {
			return Result.fail("数据错误，请刷新后重试");
		}
		return Result.SUCCESS;
	}

}
